package mylogger

import (
	"fmt"
	"os"
	"time"
)

type FileLogger struct {
	Level    Loglevel
	FilePath string
	// Name  string
}

func NewFileLogger(loglevelstring string, filepath string) FileLogger {
	level, err := parse(loglevelstring)
	if err != nil {

		panic(err)
	}
	return FileLogger{Level: level, FilePath: filepath}
}
func (f FileLogger) enableLog(loglevelstring string) (bool, string) {
	ls, err := parse(loglevelstring)
	if err != nil {
		fmt.Println(err)
	}

	if f.Level > DEBUG && ls >= f.Level {

		return true, loglevelstring
	} else if f.Level == DEBUG {
		return true, loglevelstring
	}
	return false, loglevelstring
}

func (f FileLogger) filelog(loglevelstring, filename string, a ...interface{}) {
	flag, _ := f.enableLog(loglevelstring)
	if flag {
		t := fmt.Sprint(time.Now().Format("2006-01-02-15:04:05"))
		filenameSt := f.FilePath + filename
		file, err := os.OpenFile(filenameSt, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
		if err != nil {
			fmt.Printf("open file errors : %v", err)
			os.Exit(1)
		}
		msg := fmt.Sprintf(t + "  " + "[" + loglevelstring + "]")
		_, errx := fmt.Fprintln(file, msg, a)
		if errx != nil {
			fmt.Printf("write log to file failed")
			os.Exit(1)
		}
	}
}
func (f FileLogger) INFO(a ...interface{}) {

	f.filelog("info", "info.log", a...)

}
func (f FileLogger) DEBUG(a ...interface{}) {

	f.filelog("debug", "debug.log", a...)
}
func (f FileLogger) TRACE(a ...interface{}) {

	f.filelog("trace", "trace.log", a...)
}
func (f FileLogger) WARNING(a ...interface{}) {

	f.filelog("warning", "warning.log", a...)
}
func (f FileLogger) ERROR(a ...interface{}) {

	f.filelog("error", "error.log", a...)
}
func (f FileLogger) FATAL(a ...interface{}) {

	f.filelog("fatal", "fatal.log", a...)
}
